package cyc.learn.mode.singleton.lazy;

import java.util.concurrent.atomic.AtomicInteger;

public class SingletonTest {

    public static void main(String[] args) throws InterruptedException {
//        final Singleton[] s1 = {null, null};
//
//        //使用多线程获取
//        Thread t1 = new Thread(() -> s1[0] = Singleton.getInstance());
//        Thread t2 = new Thread(() -> s1[1] = Singleton.getInstance());
//
//        t1.start();
//        t2.start();
//
//        //主线程休眠一秒钟，让t1和t2线程能先跑完。
//        Thread.currentThread().sleep(1000);
//
//        //若输出true，表示两个线程获取到的单例是同一个实例。反之，我们的单例模式就不再是单例
//        //这里会发现，获取的单例有时一样，有时不一样。
//        if (s1[0].equals(s1[1])) {
//            System.out.println(true + " " + s1[0].hashCode() + " " + s1[1].hashCode());
//        } else {
//            //但是若在获取的地方也手动让线程休眠。这样将输出false
//            System.out.println(false + " " + s1[0].hashCode() + " " + s1[1].hashCode());
//        }

        int times = 1000;
        AtomicInteger count = new AtomicInteger(0);
        Thread[] threads = new Thread[times];

        new Thread(Singleton::getInstance).start();

        for (int i = 0; i < times; i++) {
            Thread thread = new Thread("thread-" + i){
                @Override
                public void run() {
                    Singleton.getInstance();
                    count.addAndGet(1);
                    System.out.println(Thread.currentThread().getName() + " : " + count.get());
                }
            };
            threads[i] = thread;
        }

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            threads[i].start();
        }

        while (true) {
            if (count.get() >= times){
                System.out.println("获取1000个单例耗时：" + (System.currentTimeMillis() - startTime));
                break;
            }
        }
        System.out.println("结束");


    }
}
